<?php

/*
 * Copyright 2015 crackerben.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Com\Wechat\ChatService;

/**
 * 对话服务-用户管理
 */
class UserModel {

    /**
     * 创建分组
     * @param type $token
     * @param type $name 要创建的组名
     * @return boolean
     */
    public function createGroup($token, $name) {
        $url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=$token";
        $curl = new \Com\Wechat\CurlModel();
        $temp = array('name' => $name);
        $arr = array('group' => $temp);
        $result = json_decode($curl->curlSafePost($url, $arr));
        if (!isset($result->errcode)) {
            return $result->id;
        } else {
            return FALSE;
        }
    }
/**
 * 查询用户所在分组
 * @param type $token 
 * @return boolean
 */
    public function selectGroup($token) {
        $url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=$token";
        $curl = new \Com\Wechat\CurlModel();
        $result = json_decode($curl->curlSafeGet($url));
        if (!isset($result->errcode)) {
            return $result;
        } 
        else {
            return FALSE;
        }
    }
    /**
     * 修改分组名
     * @param type $token
     * @param type $id  组别id
     * @param type $name 要修改的组名
     * @return boolean
     */
     public function changeGroupName($token,$id,$name) {
        $url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=$token";
        $curl = new \Com\Wechat\CurlModel();
        $temp = array('id' => $id,'name'=>$name);
        $arr = array('group' => $temp);
        $result = json_decode($curl->curlSafePost($url, $arr));
        if ($result->errcode=='0') {
            return TRUE;
        } 
        else {
            return FALSE;
        }
     }
/**
 * 移动用户分组
 * @param type $token
 * @param type $openid 微信用户openid
 * @param type $id 组别id
 * @return boolean
 */   
     public function giveGroup($token,$openid,$id) {
        $url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=$token";
        $curl = new \Com\Wechat\CurlModel();
        $arr = array('openid' =>$openid,'to_groupid'=>$id);
        $result = json_decode($curl->curlSafePost($url, $arr));
        if ($result->errcode=='0') {
            return TRUE;
        } 
        else {
            return FALSE;
        }
     }

}
